import { onMounted, onUnmounted } from 'vue'
import axios from 'axios'

export function useWebRtcVideo(videoDom, sourceAddr) {
  let pc = null
  onMounted(async () => {
    console.log("直播开始：",sourceAddr);
    const pc = new RTCPeerConnection({})
    pc.addTransceiver("video", { direction: "recvonly" })
    pc.addTransceiver("audio", { direction: "recvonly" })
    pc.ontrack = ({ streams }) => {
      videoDom.value.srcObject = streams[0]
    }

    // 发送RTC请求
    const offer = await pc.createOffer({
      offerToReceiveVideo: true,
      offerToReceiveAudio: true,
      iceRestart: true
    });

    // 设置自身和远程的SDP(媒体协商信息)
    const reg = /webrtc:\/\/((\d*).(\d+).(\d+).(\d+)(:\d+)?)\//
    const signalServerIp = reg.exec(sourceAddr)[1]
    await pc.setLocalDescription(offer)
    // 将SDP数据通过信令服务器进行中转，数据格式：https://github.com/rtcdn/rtcdn-draft
    const {data: resp} = await axios({
      method: 'post',
      url: `http://${signalServerIp}:1985/rtc/v1/play/`,
      data: {
        streamurl: sourceAddr,
        sdp: offer.sdp
      }
    });
    await pc.setRemoteDescription(new RTCSessionDescription({ type: 'answer', sdp: resp.sdp }))

    // 通过信令服务器交换ICE信息，本地网络可以没有ICE服务器
    pc.onicecandidate = (event) => {
      // 发送给信令服务器ICE信息
      // console.log(event)
    }
  })
  onUnmounted(() => {
    pc && pc.close()
  })
}